import simpleGit from "simple-git";
import path from "path";
import fs from "fs";
import { exec, execSync } from "child_process";
import { log } from "console";
const repoUrl =
  "https://codeup.aliyun.com/66ecea0d37a6d88172290c6d/wyzx_web/overhaul-web.git";
const projectName = "overhaul";
// 当前项目
const targetPath = path.resolve("./", projectName);
const nodeModulesPath = path.resolve("./", `${projectName}/node_modules`);
const args = process.argv.slice(2);
const projectScriptName = args[0]; // 对应项目打包命令
const SCRIPT_TO_BRANCH = {
  staging: "test",
  production: "release",
};

async function cloneSpecificBranch() {
  const branchName = SCRIPT_TO_BRANCH[projectScriptName];
  console.log(
    `对应项目中打包命令(${projectScriptName}), 对应分支(${branchName})`
  );

  if (fs.existsSync(targetPath)) {
    const git = simpleGit(targetPath);
    // 判断文件夹是否存在
    // 则检出
    try {
      // 检查本地是否已存在该分支
      await checkBranchExists(git, branchName, async (val)=>{
        // 判断当前分支是不是指定分支
        if(val.current !== branchName) {
          // 如果本地存在, 则无需远程拉取
          if(val.all.includes(branchName)){
            console.info("检出本地分支", branchName);
            await git.checkout(branchName); // 检出本地分支
            console.info("更新分支", branchName);
            await updateCurrentBranch();
          } else {
            await git.checkout(['--track', `origin/${branchName}`]);
            console.log(`已检出远程分支: ${branchName}`);
          }
        } else {
          console.info("更新分支", branchName);
          await updateCurrentBranch();
        }
      })
    } catch (e) {
      console.log("e", e);
    }
  } else {
    const git = simpleGit();
    try {
      // 克隆没有问题
      // await git.clone(repoUrl, targetPath, [
      //   "-b",
      //   branchName,
      //   "--single-branch",
      // ]);
      // 克隆整个仓库
      await git.clone(repoUrl, targetPath);
      console.log("克隆整个仓库成功");
      // 拉取所有远程分支
      const gitLocal = simpleGit(targetPath);
      await checkBranchExists(gitLocal, branchName)
      await gitLocal.checkout(["--track", `origin/${branchName}`]);
      console.log(`已检出远程分支: ${branchName}`);
      await installDepByTargetDir();
    } catch (err) {
      console.error("失败:", err);
    }
  }
}
async function checkBranchExists(gitInstance, branchName, fn) {
  await gitInstance.fetch(["--all", "--prune"]);
  // 获取仓库信息
  const branches = await gitInstance.branch();
  const unionBranches = branches.all.map(item => item.replace('remotes/origin/', ''))
  const branchExists = unionBranches.all.includes(branchName);

  if (!branchExists) {
    console.log('分支不存在')
  }
  fn && fn(branches)
}
/**
 * 判断依赖并决定是否安装
 * @returns {Promise<void>}
 */
async function installDepByTargetDir() {
  process.chdir(targetPath);
  console.log(`当前工作目录为: ${process.cwd()}`, "开始安装...");
  await execSync("npm cache clean --force") // 清除缓存
  await execSync("npm i --legacy-peer-deps", async (error, stdout, stderr) => {
    if (error) {
      console.error(`执行错误: ${error.message}`);
      return;
    }
    if (stderr) {
      console.error(`标准错误输出: ${stderr}`);
      return;
    }
    console.log(`标准输出:\n${stdout}`);
  });
  await buildStart();
}

async function buildStart() {
  try {
    process.chdir(targetPath);
    console.log(`当前工作目录为: ${process.cwd()}`, "开始构建...");
    execSync(`npm run build:${projectScriptName}`, (error, stdout, stderr) => {
      if (error) {
        console.error(`执行错误: ${error.message}`);
        return;
      }
      if (stderr) {
        console.error(`标准错误输出: ${stderr}`);
        return;
      }
      console.log(`标准输出:\n${stdout}`);
    });
  } catch (err) {
    console.error(`无法进入目录: ${targetPath}`);
    console.error(err);
  }
}
// 拉取最新代码合并到当前分支
async function updateCurrentBranch(git) {
  try {
    // 获取当前分支名称
    const currentBranch = await git.revparse(["--abbrev-ref", "HEAD"]);
    console.log(`Current branch: ${currentBranch}`);

    // 拉取最新代码并合并到当前分支
    await git.pull("origin", currentBranch);

    console.log(`Updated current branch: ${currentBranch}`);
  } catch (err) {
    console.error("Error updating current branch:", err);
  }
}
await cloneSpecificBranch();
